package com.zr.utils;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author ：Zhang
 * @date ：Created in 2024/12/17 17:30
 * @description：
 * @modified By：
 * @version:
 */
public class UploadUtils {
    public static String uploadOos(MultipartFile myfile) {
        try {
            // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
            String endpoint = "oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            //   EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            DefaultCredentialProvider defaultCredentialProvider = CredentialsProviderFactory.newDefaultCredentialProvider("LTAI5tEDMPPhxLeqQzN5XnfQ", "u5J8iHaxY3KgsElrOHEnRCwnoGtD3q");
            // 填写Bucket名称，例如examplebucket。
            String bucketName = "aaa-lyk";
            // 填写Object完整路径，完整路径中不能包含Bucket名称 上传到oss的bucket中的名称
            String objectName = UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
            // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
            // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            //String filePath= "C:\\Users\\zr\\Desktop\\QQ20241211-113729.png";
            // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
            String region = "cn-hangzhou";

            // 创建OSSClient实例。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
            OSS ossClient = OSSClientBuilder.create()
                    .endpoint(endpoint)
                    .credentialsProvider(defaultCredentialProvider)
                    .clientConfiguration(clientBuilderConfiguration)
                    .region(region)
                    .build();

            try {
                InputStream inputStream = myfile.getInputStream();
                // 创建PutObjectRequest对象。
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
                // 创建PutObject请求。
                PutObjectResult result = ossClient.putObject(putObjectRequest);
                return "https://"+ bucketName + "." + endpoint + "/" + objectName;
            } catch (OSSException oe) {
                throw new RuntimeException("Caught an OSSException, which means your request made it to OSS");
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }catch (Exception e){
            throw new RuntimeException("上传失败");
        }

    }
    public String upload(MultipartFile myfile, HttpServletRequest request) throws  IOException {
        //1.获取保存文件的路径
        String realPath = request.getSession().getServletContext().getRealPath("/images");
        //2.根据上面的路径创建文件对象
        File file=new File(realPath);
        //3.判断该文件夹是否存在
        if(!file.exists()){
            file.mkdirs();
        }
        //4.获取上传文件的名称. 获取登录者ip+登录者id+登录者的时间戳
        String filename = UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
        //5.把上传的文件保存到指定服务器下的路径。
        File target=new File(realPath+"/"+filename);
        myfile.transferTo(target);
        System.out.println("上传成功");
        return "main";
    }
}
